/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.activity.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ykht.proj.activity.Enum.PlanStatusEnum;
import com.ykht.proj.activity.entity.VDiscountPlanShop;
import com.ykht.proj.activity.vo.CnGroupShopVoReq;
import com.ykht.proj.activity.vo.SjObject;
import com.ykht.proj.activity.vo.VDiscountPlanVo;
import com.ykht.proj.admin.api.feign.RemoteUserService;
import com.ykht.proj.admin.api.vo.UserVO;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.log.annotation.SysLog;
import com.ykht.proj.activity.entity.VDiscountPlan;
import com.ykht.proj.activity.service.VDiscountPlanService;
import com.ykht.proj.coupon.api.feign.RemoteShopService;
import com.ykht.proj.coupon.entity.CnShop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 优惠方案表
 *
 * @author csg
 * @date 2021-05-18 14:26:34
 */
@RestController
@AllArgsConstructor
@RequestMapping("/vdiscountplan")
@Api(value = "vdiscountplan", tags = "优惠方案表管理")
@Slf4j
public class VDiscountPlanController {

	private final VDiscountPlanService vDiscountPlanService;

	private final RemoteUserService remoteUserService;
	private final RemoteShopService remoteShopService;

	/**
	 * 优惠方案 分页查询
	 *
	 * @param page          分页对象
	 * @param vDiscountPlan 优惠方案表
	 * @return
	@PreAuthorize("@pms.hasPermission('activity_vdiscountplan_view')")
	 */
	@ApiOperation(value = "优惠方案 分页查询", notes = "优惠方案 分页查询")
	@GetMapping("/page")
	public R getVDiscountPlanPage(Page page, VDiscountPlanVo vDiscountPlanVo) {
		log.info("->优惠方案 分页查询{}", vDiscountPlanVo);
		IPage<VDiscountPlanVo> planVoIPage = vDiscountPlanService.getVDiscountPlanPage(page, vDiscountPlanVo);
		return R.ok(planVoIPage);
	}


	/**
	 * 根据协议ID获取  协议和公司详情
	 *
	 * @param vDiscountPlan 优惠方案表
	 * @return
	 */
	@ApiOperation(value = "根据协议ID获取  协议和公司详情", notes = "根据协议ID获取  协议和公司详情")
	@GetMapping("/getByIdDiscountPlan")
	public R getByIdDiscountPlan(Long id) {
		log.info("->根据协议ID获取  协议和公司详情{}", id);
		VDiscountPlanVo vDiscountPlanVo = vDiscountPlanService.getByIdDiscountPlan(id);
		if (null != vDiscountPlanVo.getLoginId()) {
			UserVO byIdUser = remoteUserService.getByIdUser(vDiscountPlanVo.getLoginId());
			vDiscountPlanVo.setUsername(byIdUser.getUsername());
			vDiscountPlanVo.setPhone(byIdUser.getPhone());
		}
		return R.ok(vDiscountPlanVo);
	}


	/**
	 * 通过id查询优惠方案表
	 *
	 * @param id id
	 * @return R
	@PreAuthorize("@pms.hasPermission('activity_vdiscountplan_view')")
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}")
	public R getById(@PathVariable("id") Long id) {
		VDiscountPlan discountPlan = vDiscountPlanService.getById(id);
		VDiscountPlanVo vDiscountPlanVo = BeanUtil.toBean(discountPlan, VDiscountPlanVo.class);
		List<VDiscountPlanShop> discountPlanShopList = new VDiscountPlanShop().selectList(
				Wrappers.lambdaQuery(VDiscountPlanShop.class).eq(VDiscountPlanShop::getDiscountPlanId, id));
		if (discountPlanShopList != null && discountPlanShopList.size() > 0){
			List<Long> collect = discountPlanShopList.stream().map(VDiscountPlanShop::getShopId).collect(Collectors.toList());
			List<String> shopIdList = new ArrayList<>();
			collect.stream().forEach(itme -> {
				shopIdList.add(itme.toString());
			});
			String[] objects = new  String[shopIdList.size()];
			shopIdList.toArray(objects);
			List<CnShop> shopList = remoteShopService.getByIds(objects);
			List<SjObject> sjObjectList = new ArrayList<>();
			shopList.stream().forEach(itme ->{
				SjObject sjObject = BeanUtil.toBean(itme, SjObject.class);
				sjObject.setShopId(itme.getId());
				sjObjectList.add(sjObject);
			});
			vDiscountPlanVo.setSjObjectList(sjObjectList);
		}
		return R.ok(vDiscountPlanVo);
	}

	/**
	 * 新增优惠方案表
	 *
	 * @param vDiscountPlanVo 优惠方案表
	 * @return R
	 */
	@ApiOperation(value = "新增优惠方案表", notes = "新增优惠方案表")
	@SysLog("新增优惠方案表")
	@PostMapping
//    @PreAuthorize("@pms.hasPermission('activity_vdiscountplan_add')" )
	public R save(@RequestBody VDiscountPlanVo vDiscountPlanVo) {
		log.info("->新增优惠方案表{}", vDiscountPlanVo);
		if (vDiscountPlanVo.getPlanEndTime().isBefore(LocalDateTime.now())) {
			return R.failed("方案结束时间要大于当前日期");
		}
		if (LocalDateTime.now().isBefore(vDiscountPlanVo.getPlanStaTime())) {
			vDiscountPlanVo.setPlanStatus(PlanStatusEnum.TO_START.getValue());
		} else {
			vDiscountPlanVo.setPlanStatus(PlanStatusEnum.AT_WORK.getValue());
		}
		if (null == vDiscountPlanVo.getSjObjectList() || vDiscountPlanVo.getSjObjectList().size() == 0) {
			return R.failed("请选择参加优惠方案的门店");
		}
		vDiscountPlanService.addVDiscountPlan(vDiscountPlanVo);
		return R.ok();
	}


	@ApiOperation(value = "校验 优惠方案名称")
	@PostMapping("/checkPlanName")
	public R checkSjName(@RequestBody VDiscountPlan vDiscountPlan) {
		log.info("->校验 优惠方案名称{}", vDiscountPlan);
		VDiscountPlan discountPlan = new VDiscountPlan().selectOne(Wrappers.lambdaQuery(VDiscountPlan.class)
				.eq(VDiscountPlan::getPlanName, vDiscountPlan.getPlanName()));
		return R.ok(discountPlan == null ? true : discountPlan.getId().equals(vDiscountPlan.getId()) ? true : false);
	}


	/**
	 * 修改优惠方案表
	 *
	 * @param vDiscountPlan 优惠方案表
	 * @return R
	 */
	@ApiOperation(value = "修改优惠方案表", notes = "修改优惠方案表")
	@SysLog("修改优惠方案表")
	@PutMapping
//    @PreAuthorize("@pms.hasPermission('activity_vdiscountplan_edit')" )
	public R updateById(@RequestBody VDiscountPlanVo vDiscountPlanVo) {
		log.info("->修改优惠方案表{}", vDiscountPlanVo);
		if (vDiscountPlanVo.getPlanEndTime().isBefore(LocalDateTime.now())) {
			return R.failed("方案结束时间要大于当前日期");
		}
		if (LocalDateTime.now().isBefore(vDiscountPlanVo.getPlanStaTime())) {
			vDiscountPlanVo.setPlanStatus(PlanStatusEnum.TO_START.getValue());
		} else {
			vDiscountPlanVo.setPlanStatus(PlanStatusEnum.AT_WORK.getValue());
		}
		if (null == vDiscountPlanVo.getSjObjectList() || vDiscountPlanVo.getSjObjectList().size() == 0) {
			return R.failed("请选择参加优惠方案的门店");
		}
		vDiscountPlanService.updateVDiscountPlan(vDiscountPlanVo);
		return R.ok();
	}

	/**
	 * 通过id删除优惠方案表
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除优惠方案表", notes = "通过id删除优惠方案表")
	@SysLog("通过id删除优惠方案表")
	@DeleteMapping("/{id}")
//    @PreAuthorize("@pms.hasPermission('activity_vdiscountplan_del')" )
	public R removeById(@PathVariable Long id) {
		log.info("->通过id删除优惠方案表{}", id);
		vDiscountPlanService.deleteDiscountPlan(id);
		return R.ok();
	}

	/**
	 * 创建群组取门店列表（根据品牌标签, 品牌/门店名, 地址查询,协议类型)
	 *
	 * @param cnDiscountShopVoReq 条件
	 * @return R
	 */
	@ApiOperation(value = "创建群组取门店列表（根据品牌标签, 品牌/门店名, 地址查询,协议类型)", notes = "创建群组取门店列表（根据品牌标签, 品牌/门店名, 地址查询,协议类型)")
	@SysLog("创建群组取门店列表（根据品牌标签, 品牌/门店名, 地址查询,协议类型)")
	@PostMapping("getByGroupShop")
	public R<Page<CnGroupShopVoReq>> getByGroupShop(@RequestBody CnGroupShopVoReq cnGroupShopVoReq) {
		Page<CnGroupShopVoReq> groupShopVoReqList = vDiscountPlanService.getByGroupShop(cnGroupShopVoReq.getPage(), cnGroupShopVoReq);
		return R.ok(groupShopVoReqList);
	}

}
